WA3358 Security Fundamentals for Software Engineers

1. Security Concepts

1.1. Introduction

  • Developing secure software is as much a philosophy as a skill

  • As developers we’re often asked to “Make it work!”

  • Later we work on “Make it safe!”

  • This course aims to get you thinking earlier about security in the design and development process

notes: DevOps and DevSecOps are big buzzwords. In general the idea is find bugs or vulnerabilities earlier in the design and development process and provide open communication about the issues, risks, and corrections of those issues to everyone in the DevOps cycle.

1.2. CIA Triad

CIA Triad
  • Confidentiality

    • Determines the secrecy of the information asset.

  • Integrity

    • Provides the assurance that the data is accurate and reliable.

  • Availability

    • The ability of the users to access an information asset.

1.3. Confidentiality

Confidential
  • Protection of disclosure to unauthorized parties

  • Any information leak can be catastrophic

  • Includes protection from disclosure of:

    • stored data

    • restricted data

    • communication traffic

    • communication content

1.4. Integrity

Checkmark
  • Protection of information from alteration, creation, or destruction by unauthorized parties

  • Any alteration or threat of alteration may be catastrophic

  • Includes protection from:

    • data file modification

    • program file modification

    • replication, altering, deleting, creating new or false data

1.5. Availability

Twenty-four
  • Assurance that systems and system resources will be accessible when needed

  • Attacks often called DoS (Denial of Service)

  • A temporary restriction of access

    • Permanent restriction is failure of integrity

  • Includes protection from:

    • Excessive requests impeding ability to serve clients

    • System rendered inoperable by removal of files/components/applications

    • Overloading parts of the system leading to crashes

1.6. Authentication, Authorization, and Accounting (AAA)

  • A three-process framework

    • Used to manage user access

    • Enforce user policies and privileges

    • Measure the consumption of network resources

1.7. Identification

  • The unproven assertion of who you are

  • For example:

    • A username

    • An ID card

    • A bank card

1.8. Authentication

  • A user providing information about who they are and proving it

  • Users or systems present login credentials that affirm they are who they claim to be

1.9. Authorization

  • Authorization follows authentication

  • A user can be granted privileges to access certain areas of a network, application, or system

  • Areas and sets of permissions granted a user are often stored in a database along with the user’s identity

  • The user’s privileges can be changed by an administrator or developer with access to the database

1.10. Accounting

  • Tracking user activity while users interact with the system

  • Often logging what data accessed or services used

  • May be used to:

    • Analyze user trends

    • Audit user activity

    • Provide early warning of misuse

1.11. Principle of Least Privilege

  • AKA principle of minimal privilege (PoMP) or the principle of least authority (PoLA)

  • Every entity (such as a process, a user, or a program) must be able to access only the information and resources that are necessary for its legitimate purpose

1.12. Separation of Duties

  • Ensures one individual cannot complete a critical task by themselves

  • Reduces the possibility for fraud, sabotage, theft or general abuse

  • Requires collusion of two or more parties to circumvent

1.13. Non-repudiation

  • Provides proof of the origin, authenticity, and integrity of data.

  • Ensures that no party can deny sending or receiving a message

  • Ensures no party can contest the authenticity of their signature on a document

1.14. Defense in Depth

  • A cybersecurity approach that involves layering multiple defensive mechanisms to protect valuable data and information

  • If one mechanism fails, there are other layers of defense in place to prevent or mitigate an attack

  • Addresses different attack vectors and provides a more robust and resilient security posture

1.15. Defense in Depth as a Developer

  • Follow secure coding practices

  • Stay updated on the latest security vulnerabilities

  • Learn best practices in web application security

1.16. Software Security Terminology

  • Asset

    • The object which requires protection

  • Attack path

    • The mechanism taken by an attacker to access an asset

  • Attack surface

    • The sum of all the possible attack paths

1.17. Software Security Terminology

  • Defects/weaknesses

    • Errors that could result in unexpected or undesired behavior

  • Vulnerability

    • A defect that can be exploited to compromise a system

  • Threats

    • A harm that might be caused by an attacker

  • Exploit

    • When an attacker uses a vulnerability to cause harm

1.18. Common Threats

  • Hackers

  • Users

  • Insiders

1.19. Common Attacks

  • Buffer overflow

  • Command injection

  • SQL injection

  • Cross site scripting

2. Zero Trust

Objectives

Key objectives of this chapter

  • Learn about the Zero Trust model

  • Discuss how Zero Trust applies to application development

2.1. Zero Trust

  • An evolving set of cybersecurity paradigms

  • A security framework that requires all users to be authenticated, authorized, and continuously validated before being granted access to resources

  • Assumes no implicit trust granted to assets or user accounts based solely on their physical or network location

  • The main mantra: Never Trust! Always Verify!

2.2. Zero Trust Core Principles

  • Never trust, always verify

  • Principle of least privilege

  • Move security away from the perimeter to the application itself

  • Continuous monitoring and analytics

  • Embrace adaptability and flexibility

2.3. Never Trust, Always Verify

  • Systems operating under a Zero Trust framework do not initially trust access or transactions from anyone, including internal users

  • Always authenticate and authorize based on all available data points, including

    • User identity

    • Location

    • Service or workload

    • Data classification

    • Any anomalies

2.4. Assume Breach

  • Minimize blast radius and segment access to modules or components of your application

  • Verify end-to-end encryption

  • Use analytics to get visibility, drive threat detection, and improve defenses

2.5. Apply Least-privilege

  • Limit user access with

    • Just-in-time

    • Just-enough access

    • Risk-based adaptive polices

    • Data protection to help secure both data and productivity

  • This applies to insiders as well!

2.6. The Zero Trust Maturity Model

zero trust maturity model

2.7. Identities

Verify and secure each identity with strong authentication across your entire digital estate.

2.8. Devices

  • Gain visibility into devices accessing the network.

  • Ensure compliance and health status before granting access.

2.9. Network

  • Ensure that devices and users aren’t trusted just because they’re on an internal network.

  • Encrypt all internal communications, limit access by policy, and employ micro-segmentation and real-time threat detection.

2.10. Applications and Workloads

  • Discover shadow IT, ensure appropriate in-app permissions, gate access based on real-time analytics, and monitor and control user actions.

  • Use telemetry to detect attacks and anomalies, automatically block and flag risky behavior, and employ least-privilege access principles.

2.11. Data

  • Move from perimeter-based data protection to data-driven protection.

  • Use intelligence to classify and label data.

  • Encrypt and restrict access based on organizational policies.

2.12. Zero Trust and Developers

  • Incorporate Zero Trust principles throughout the development cycle

  • Not a replacement for security fundamentals, developers should still follow best practices

  • Manage and secure data where no actual perimeter exists such as cloud services

  • Developers should verify the security of open source and third-party components used in their projects and apply updates and fixes as necessary

3. OWASP Top Ten

Objectives

Key objectives of this chapter

  • Learn about the Open Web Application Security Project

  • Discuss tools and approaches to mitigate OWASP vulnerabilities

3.1. The OWASP Top Ten

OWASP Logo

The Open Web Application Security Project formed in 2003, a foundation that focuses on software security. It supports the security industry with the OWASP Top 10.

3.2. OWASP Top 10

Vulnerability Description

1. Broken access control

failures can jeopardize information disclosures and data integrity

2. Cryptographic failures

concerns data exposure and compromises confidentiality

3. Injection

involves hostile data use, attacks, and unsafe queries

4. Insecure design

covers weaknesses and flaws in control designs

5. Security misconfiguration

involves features that are incorrectly enabled or have other configuration

3.3. OWASP Top 10

Vulnerability Description

6. Vulnerable and outdated components

involve version control and other compatibility issues

7. Identification and authentication failures

covers password issues, automated attacks like credential stuffing, and session

8. Software and data integrity failures

involve integrity violations, which are often from untrusted sources

9. Security and logging and monitoring failures

involve detecting and responding to breaches

10. Server-side request forgery

results in URL validation failures

3.4. OWASP Testing Framework

  • Activities that should take place:

    • Before development begins

    • During definition and design

    • During development

    • During deployment and

    • During maintenance and operations

3.5. 2021 OWASP Top 10 Details

owasp top 10

3.6. Injection

  • Injection attacks occur when untrusted data is sent to an interpreter

  • Can lead to data loss, corruption, or unauthorized data disclosure

  • Includes SQL injection where user input constructs a SQL query without proper validation or escaping

3.7. Broken Authentication

  • Incorrect implementation of session management and authentication functions

  • May compromise passwords, keys, or session tokens

  • Weak password enforcement can lead to unauthorized access

3.8. Sensitive Data Exposure

  • Occurs when sensitive data is inadequately protected

  • Transmitting sensitive data over HTTP instead of HTTPS can lead to exposure

3.9. XML External Entity (XXE)

  • XXE attacks happen with XML input containing external entity references

  • Can result in disclosure of internal files, denial of service, or remote code execution

3.10. Broken Access Control

  • Flaws in enforcing restrictions on authenticated users

  • Allows attackers to access unauthorized functionality or data

3.11. Security Misconfigurations

  • Using default or incomplete configurations can lead to unauthorized access

  • Misconfigurations can expose private information, such as directory listing vulnerabilities

3.12. Cross-Site Scripting (XSS)

  • Flaws in adding untrusted data to web pages

  • Attackers can execute malicious scripts, hijack sessions, deface websites, or redirect users

3.13. Insecure Deserialization

  • Insecure deserialization allows remote code execution

  • Can lead to replay attacks, injection attacks, and privilege escalation

3.14. Insufficient Logging & Monitoring

  • Inadequate logging and monitoring give attackers opportunities to persist and pivot

  • Proper logging and monitoring are crucial for timely detection and response

4. Encryption and Decryption

Objectives

Key objectives of this chapter

  • Learn some key principles of cryptography

  • Understand hashing

  • Understand digital certificates and their use

4.1. Encryption and Decryption

encryption and decryption

4.2. Three Key Ideas

  • Confusion (substitution )

  • Diffusion (transposition)

  • Secrecy only in the key

4.3. Terminology

  • Encryption - the method of transforming data (plaintext) into an unreadable format

  • Plaintext - the format (usually readable) of data before being encrypted

  • Ciphertext - the "scrambled" format of data after being encrypted

4.4. Cryptographic Terminology

  • Decryption - the method of turning cipher text back into plaintext

  • Encryption algorithm a set or rules or procedures that dictates how to encrypt and decrypt data, also called an encryption cipher

  • Key - (cryptovariable) a value used in the encryption process to encrypt and decrypt

4.5. Symmetric Encryption

symmetric encryption

4.6. Some Common Symmetric Algorithms

  • AES (Advanced Encryption Standard): AES is widely used and considered secure. It supports key sizes of 128, 192, and 256 bits.

  • ChaCha20: ChaCha20 is a stream cipher that is gaining popularity due to its speed and security.

4.7. Asymmetric Encryption

assymetric encryption

4.8. Common Asymmetric Algorithms

  • RSA (Rivest-Shamir-Adleman)

  • Elliptic Curve Cryptography (ECC)

  • Diffie-Hellman Key Exchange (DH

  • DSA (Digital Signature Algorithm)

  • ECDSA (Elliptic Curve Digital Signature Algorithm)

  • ElGamal

4.9. Hashing

  • Hashing is a one-way operation

  • Converts a large amount of data into a fixed length value (hash digest)

4.10. Secure Hashing Algorithm

  • Family of cryptographic functions published by NIST

  • SHA-3 (formerly Keccak) is the most recent

  • Used to establish integrity

  • Combined with encryption algorithms can be used as part of a digital signature

4.11. Public Key Infrastructure

  • A set of hardware, software, people, policies, and procedures needed to create, manage, distribute, use, store, and revoke digital certificates

  • Enables C and I of the CIA triad

  • Enables non-repudiation

4.12. Digital Certificates

  • Each person or server can have a digital certificate

  • Has information about a person, including a person’s public key

  • Typically, not attached to a person but to a server or system

4.13. Certificate Authorities

  • Certificates are signed by a Certificate Authority

  • The Certificate Authority vouches for each organization’s certificate

  • Some certificates can be self-signed

  • Typically, organizations purchase wildcard certificates from authorities such as Let’s Encrypt, Verisign, or Thawte

4.14. X.509 Certificates

  • A standard format for public key certificates

  • Applications:

    • SSL/TLS

    • Signed and encrypted email

    • Code signing

    • Document signing

    • Client authentication

    • Government-issued electronic IDs

4.15. Parts of a certificate

  • A public key

    • Part of a key pair that also includes a private key

    • Private key is kept secure

    • Only the public key is included in the certificate

  • A digital signature

    • Information about both the identity associated with the certificate and its issuing certificate authority (CA)

    • An encoded hash (fixed-length digest) of a document that has been encrypted with a private key

  • Fields specifying the subject, issuing CA, validity and other and other required information

4.16. Secure Sockets Layer/Transport Security Layer

  • Encrypt data in transit

  • Its successor is TLS (Transport Layer Security)

  • Both are protocols for establishing authenticated and encrypted links between networked computers

  • Encrypts plaintext, like passwords, and credit card numbers

  • Only the user and the website can decrypt

  • Ensures the data remain unchanged

  • Authenticates websites

  • Modern browsers show warnings when the connection is NOT entirely secure

4.17. SSL (TLS) Certificate

  • Identify an individual, server, or organization

  • A digital document that binds the identity of a website to a cryptographic key pair

  • The key pair consists of a public key and a private key

  • The public key, included in the certificate, allows a web browser to initiate an encrypted communication session with a web server via the TLS and HTTPS protocols

  • The private key is kept secure on the server, and is used to digitally sign web pages and other documents (such as images and JavaScript files)

4.18. HTTPS

  • HTTPS (Hypertext Transfer Protocol Secure) is a secure version of the HTTP protocol

  • Uses the SSL/TLS protocol for encryption and authentication

  • HTTPS is specified by RFC 2818 (May 2000) and uses port 443 by default instead of HTTP’s port 80

4.19. HTTPS Provides

  • Encryption

  • Authentication

  • Integrity

  • Validation

    • Domain validation (DV)

    • Organization/Individual validation (OV/IV)

    • Extended validation (EV)

4.20. How does HTTPS work?

  • Adds encryption to the HTTP protocol by wrapping HTTP inside the SSL/TLS protocol

    • Which is why SSL is called a tunneling protocol)

  • All messages are encrypted in both directions between two networked computers including:

    • Request URL (which web page was requested by the client)

    • Website content

    • Query parameters

    • Headers

    • Cookies

4.21. HTTPS and Certificates

  • Uses digital documents known as X.509 certificates

  • Binds cryptographic key pairs to the identities of entities such as websites, individuals, and companies

  • Each key pair includes

    • a private key, which is kept secure

    • a public key, which can be widely distributed

  • Anyone with the public key can use it to:

    • send data that only the private key possessor can decrypt

    • confirm that data has been digitally signed by the corresponding private key

4.22. Digital Signatures

signing verification transparent

4.23. Code-signing Certificates

Property Code-signing SSL/TLS

Purpose

Digitally sign software code, ensuring its integrity and authenticity

Used to establish secure encrypted connections between a client (such as a web browser) and a server

Protection

Protect end-users by guaranteeing the integrity of the code they download

Protect end-users by securing communication between their browsers and websites

Outcome

Verifies that the code has not been tampered with and comes from a trusted source

Ensures that the communication between the client and server is encrypted and secure, protecting sensitive data during transmission

5. Authentication and Authorization

Objectives

Key objectives of this chapter

  • Learn authentication factors

  • Explain the difference between Authentication and Authorization

  • Understand Single Sign-On

  • Introduce OAuth

5.1. What is Authentication?

  • The process of verifying the identity of a given user or client

  • Making sure that they really are who they claim to be

  • Most websites are exposed to anyone who is connected to the internet by design

  • Robust authentication mechanisms are vital to effective web security

5.2. Authentication Factors

  • something you know

  • something you have

  • something you are or do

5.3. Authentication vs. Authorization

  • Authentication

    • Verifying that a user really is who they claim to be

  • Authorization

    • Verifying whether a user is allowed to do something

5.4. Introduction to Single Sign-On (SSO)

  • Allows users to log in to one application and be automatically signed in to other applications, regardless of platform or domain

  • Provides a seamless user experience

  • Eliminates the need to remember multiple credentials for different applications.

  • Example: Google’s SSO - logging in to Gmail automatically authenticates the user to YouTube, AdSense, Google Analytics, and more

5.5. SSO Workflow

  • Users log in to one domain, which serves as the authentication domain.

  • Authentication Domain: The domain responsible for verifying user credentials.

  • Redirection: When accessing a domain requiring authentication, users are redirected to the authentication domain.

  • Already Logged-In Users: If already logged in at the authentication domain, users are immediately redirected back to the original domain without signing in again.

5.6. Single Logout (SLO)

  • Logging out of one application automatically logs the user out of all associated applications.

  • Example: Logging out of Gmail also logs the user out of other Google apps.

  • Benefit of SLO: Ensures a secure logout process across all applications.

5.7. Advantages of SSO

  • Advantages of SSO:

    • Enhanced User Experience: Users only need to log in once for access to all applications.

    • Simplified Credential Management: No need to remember separate login details for each app.

    • Increased Security: Centralized authentication and logout process.

5.8. Implementing SSO for MERN Stack

  • Implementing SSO for MERN Stack:

    1. Choose a reliable SSO solution.

    2. Integrate the SSO solution into your MERN application.

    3. Configure authentication and redirection domains.

    4. Test the SSO functionality thoroughly.

5.9. Choose an SSO provider

  • Select an SSO provider that fits your project requirements

  • Popular options include Auth0 and Okta

  • Follow the provider’s documentation to create an account, set up an application, and configure the necessary settings

5.10. Authentication and Authorization in MERN

  • Build user authentication functionality in your MERN stack application using a popular library like Passport.js or JSON Web Tokens (JWT)

  • Establish user roles and permissions to control access to different parts of your application

5.11. Integrate SSO into your application

  • Utilize the SDKs or libraries provided by your chosen SSO provider to integrate SSO functionality into your application

  • Implement the necessary code and configurations to enable SSO login and logout flows

5.12. Test and secure your SSO implementation:

  • Thoroughly test your SSO implementation to ensure seamless authentication and authorization across your application

  • Implement appropriate security measures like using HTTPS, securely storing and handling user data, and applying necessary security best practices.

5.13. OAuth 2

  • An authorization framework that enables applications — such as Facebook, GitHub, and DigitalOcean — to obtain limited access to user accounts on an HTTP service

  • Works by delegating user authentication to the service that hosts a user account and authorizing third-party applications to access that user account

  • OAuth 2 provides authorization flows for web and desktop applications, as well as mobile devices

5.14. OAuth Roles

  • Resource Owner: the user who authorizes an application to access their account. The application’s access to the user’s account is limited to the scope of the authorization granted (e.g. read or write access)

  • Client: the application that wants to access the user’s account. Before it may do so, it must be authorized by the user, and the authorization must be validated by the API.

  • Resource Server: The resource server hosts the protected user accounts.

  • Authorization Server: The authorization server verifies the identity of the user then issues access tokens to the application.

5.15. OAuth Protocol Flow

OAutho abstract flow

5.16. OpenID Connect

  • An interoperable authentication protocol based on the OAuth 2.0 framework of specifications (IETF RFC 6749 and 6750)

  • Simplifies the way to verify the identity of users based on the authentication performed by an Authorization Server

  • Obtains user profile information in an interoperable and REST-like manner

5.17. OpenID Connect

  • Enables application and website developers to launch sign-in flows and receive verifiable assertions about users across Web-based, mobile, and JavaScript clients

  • Is extensible to support a range of optional features such as encryption of identity data, discovery of OpenID Providers, and session logout

6. IAM and PAM

Objectives

Key objectives of this chapter

  • Understand the importance of Identity and Access Management

  • Learn about Privileged Access Management

  • Discuss tools for IAM and PAM

6.1. Identity and Access Management (IAM)

  • A security discipline that focuses on controlling and managing user access to resources within an organization

  • For MERN developers, plays a crucial role in ensuring that the right individuals or job roles have the appropriate access to the tools and functionalities they need to perform their tasks

6.2. Identity Management:

  • Confirming and storing information about a user’s identity, such as their job title and permissions

  • Ensures that the user is who they claim to be and authenticates their identity

  • An identity management database holds information about the user’s identity and attributes

6.3. Access Management:

  • Uses the information from identity management to determine what resources and functionalities a user is allowed to access

  • Controls and monitors network access, ensuring that users have the necessary permissions to perform their tasks

  • Access management systems manage a range of identities, including people, software, and hardware devices

6.4. Authorization:

  • The process of determining what actions a user can perform within an application based on their identity, roles, and permissions

  • Granting or denying access to specific resources or functionalities based on the user’s authorization level

6.5. Privileged Account Management (PAM)

  • Privileged accounts: accounts with elevated permissions that have access to critical systems, sensitive data, and administrative functions

  • For these accounts, PAM

    • Manages

    • Secures

    • Controls

    • Monitors

6.6. PAM User Audience

  • Designed for managing access for

    • privileged users

    • system administrators

    • IT staff

    • other users with elevated privileges

6.7. PAM Access Control

  • focuses on securing and controlling access to privileged accounts

  • enforces the principle of least privilege

  • implements additional security measures:

    • session monitoring

    • password management

    • multi-factor authentication for privileged users

6.8. PAM and IAM Compared

  • IAM manages user identities, authentication, and authorization for all users within an organization

  • IAM controls access to resources such as applications, databases, and network resources based on user roles, permissions, and policies

  • PAM is a subset of IAM that specifically focuses on managing access to privileged accounts and critical resources

6.9. PAM and IAM Compared

  • PAM systems enforce stricter controls and monitoring for privileged accounts to prevent unauthorized access and mitigate the risk of insider threats

  • PAM helps organizations implement the principle of least privilege, granting privileged access only when necessary and for a limited time

  • IAM and PAM are both important for maintaining security, compliance, and effective access management strategies within an organization

6.10. IAM Tools and Libraries

  • Okta: A popular IAM platform that provides authentication, authorization, and user management capabilities

  • Auth0: A flexible IAM solution that offers features like single sign-on (SSO), social login, and user management

  • Keycloak: An open-source IAM solution that provides features like SSO, user federation, and identity brokering

  • AWS IAM: Amazon Web Services Identity and Access Management (IAM) service for managing access to AWS resources

6.11. PAM Tools and Libraries

  • CyberArk: A leading PAM solution that offers features like password management, session monitoring, and privileged session recording.

  • BeyondTrust Privilege Management: A PAM solution that focuses on managing and securing privileged access to critical resources.

  • Thycotic Secret Server: A PAM solution that provides secure storage and management of privileged account credentials.

  • HashiCorp Vault: A popular open-source tool for managing secrets and protecting privileged access

7. Secrets Management

Objectives

Key objectives of this chapter

  • Learn about secrets

  • Discuss techniques to manage secrets

  • Explore tools to protect and use secrets

7.1. Secrets Management Guidelines

  • Apply a strong management policy to passwords, tokens, keys, and other privileged information

  • Separate secrets from source code

  • Use a secure configuration approach

  • Employ encryption for secrets

  • Use secrets management tools

  • Follow other security best practices

7.2. Separate Secrets from Source Code

  • Never hardcode sensitive information (such as API keys, database credentials, or passwords) directly into your source code

  • Use environment variables or a secrets management solution to store and access these secrets securely

  • Consider using a tool like dotenv to load environment variables from a .env file during development

7.3. Use a Secure Configuration Approach

  • Implement a configuration module or file that holds your secrets and configuration settings

  • Ensure that this configuration file is properly protected and only accessible to authorized users

  • Avoid committing the configuration file to your version control system (e.g., Git) to prevent accidental exposure

  • Use techniques like .gitignore to exclude sensitive files

7.4. Employ Encryption for Secrets

  • Encrypt sensitive data at rest, such as credentials stored in databases or files

  • Consider using encryption libraries or frameworks provided by your chosen MERN stack components (e.g., bcrypt for password hashing in Node.js, or built-in encryption features of MongoDB)

  • Encrypt sensitive data in transit using secure communication protocols (e.g., HTTPS) and encryption libraries (e.g., SSL/TLS)

7.5. Utilize Secrets Management Tools

  • Take advantage of secrets management tools specifically designed for developers, such as HashiCorp Vault or AWS Secrets Manager

  • These tools offer secure storage, retrieval, and rotation of secrets, as well as access control and audit logs

  • Integrate these tools into your MERN stack application by utilizing appropriate client libraries or SDKs

7.6. Follow Security Best Practices

  • Regularly update and patch dependencies and libraries used in your MERN stack application to mitigate security vulnerabilities

  • Implement proper authentication and authorization mechanisms to ensure only authorized users can access sensitive data and perform privileged actions

  • Implement secure coding practices, such as input validation, output encoding, and protection against common web application vulnerabilities like cross-site scripting (XSS) and SQL injection

8. JSON Web Tokens

Objectives

Key objectives of this chapter

  • Examine JSON Web Tokens (JWT)

  • Discuss the correct use of JWTs

8.1. JSON Web Tokens (JWT)

jwt contents

8.2. JWT Guidelines

  • Use JWT for user authentication and authorization

  • Implement JWT in the backend

  • Store JWT securely on the client-side

  • Refresh and revoke JWTs

8.3. JSON Web Tokens Best Practices

  • Cryptography and hashing algorithms should not be implemented from scratch

    • Best to use battle-tested libraries like CryptoJS.

  • Server should handle the signing and verification of JWTs, it is the only place that can securely handle secrets and properly verify tokens

  • If any part of the payload is altered, the signature will change, which helps ensure the integrity of the JWT and prevents tampering

  • JWTs can be transmitted in the URL bar but should be handled carefully to ensure URL safety and prevent potential issues with certain characters

8.4. Signing JWTs

  • Use a library like JSON Web Token from npm rather than writing the signing code manually

  • Install using npm

  • Import into the project using import * as jwt from 'jsonwebtoken'

  • Use a strong, long, and complex secret key

  • Token payload includes claims such as “sub” for subjects and “iss” for issuer

8.5. Signing Tokens

  • Use the jwt.sign() method

  • Pass payload, secret key, and any additional options as arguments to this method

  • Set an expiration time for the token using the “exp” claim

  • After signing the token, optionally log to the console or process further

8.6. JWT Dos

  • Do use long, strong, and unguessable secrets (e.g., 256-bit) for signing tokens

  • Do keep the token payload small to reduce the token size

  • Do ensure that HTTPS is used to secure the connection

8.7. JWT Don’ts

  • Don’t store tokens in local storage

  • Don’t store secret keys used for signing tokens in the browser

  • Don’t decode tokens on the client side, especially access tokens

  • Don’t put anything in the body of a JWT that the user/client should not be able to see

9. Risk Management, Governance, and Compliance

Objectives

Key objectives of this chapter

  • Learn general secure architecture design principles

  • Learn about the NIST Cybersecurity Framework

  • Explore open source vulnerability management tools

9.1. Secure Architecture and Design General Principles

  • Use enterprise tools and patterns

  • Protect sensitive data

  • Think Zero Trust!

  • Provide Resiliency (backup/restore)

  • Server-side validation

  • Isolate security functions

  • Application partitioning

  • Re-authorize high-value transactions

  • Provide logging and monitoring

9.2. Secure Architecture and Design for MERN Principles

  • Implement user authentication and authorization

  • Protect against cross-site scripting (XSS) attacks

  • Prevent cross-site request forgery (CSRF) attacks

  • Securely handle and store sensitive data

  • Regularly update and patch dependencies

9.3. Supply Chain Security

  • Understand and vet open-source resources and third-party tools

  • Regularly update dependencies

  • Verify package authenticity

  • Implement secure coding practices

  • Continuously monitor for vulnerabilities

9.4. NIST Cybersecurity Framework

  • Provides a set of guidelines, best practices, and standards for managing and improving cybersecurity risk

  • Helps organizations assess and enhance their cybersecurity posture by focusing on five core functions

    • Identify

    • Protect

    • Detect

    • Respond

    • Recover

9.5. Identify

identify
  • Identify critical enterprise processes and assets

  • Document information flows

  • Maintain hardware and software inventory

  • Establish policies for cybersecurity that include roles and responsibilities

  • Identify threats, vulnerabilities, and risk to assets

9.6. Protect

protect
  • Manage access to assets and information

  • Protect sensitive data

  • Conduct regular backups

  • Protect your devices

  • Manage device vulnerabilities

  • Train users

9.7. Detect

detect
  • Test and update detection processes

  • Maintain and monitor logs

  • Know the expected data flows for your enterprise

  • Understand the impact of cybersecurity events

9.8. Respond

respond
  • Ensure response plans are tested

  • Ensure response plans are updated

  • Coordinate with internal and external stakeholders

9.9. Recover

recover
  • Communicate with internal and external stakeholders

  • Ensure recovery plans are updated

  • Manage public relations and company reputation

9.10. Open-source Vulnerability Management

  • Identifies vulnerabilities in software and systems

  • Guides risk assessment

  • Provides steps for patching and mitigation

  • Useful for continuous monitoring

  • Provides a collaborative and engaged community

10. Data Classification and Protection

Objectives

Key objectives of this chapter

  • Discuss the importance of labeling and classifying data

  • Learn Travelers data classifications

10.1. Classification Controls

  • Add access controls

  • Encrypt data in transit and at rest

  • Log and audit data access

  • Periodically review classifications

10.2. Define and Document

  • Backup and restoration procedures

  • Change control procedures

  • Proper data disposal

10.3. Travelers Data Classifications

secrecy

10.4. Restricted information

  • Highly sensitive information

  • Unauthorized use or disclosure could seriously and adversely impact Travelers, its business or its competitive advantage.

10.5. Regulated Personal Information

  • Warrants special protection and is identified by Travelers Policy

10.6. Confidential information

  • Sensitive information whose unauthorized use or disclosure could negatively impact Travelers, its business, or its competitive advantage

  • Includes identifiable personal information that does not meet the definition of Regulated Personal Information

10.7. Internal information

  • Commonly shared within Travelers

  • Does not meet the standard for Restricted information, Regulated Personal Information, or Confidential information but is nevertheless not intended for distribution outside Travelers

10.8. Public information

  • Is or has been made freely available outside of Travelers or is intended for public use

11. Threat Modeling

Objectives

Key objectives of this chapter

  • Discuss steps to create a threat model for an application

  • Learn about various threat model techniques such as STRIDE or DREAD

11.1. Basic Steps

  1. Decompose the application

  2. Determine and rank threats

  3. Determine countermeasures and mitigations

11.2. 1. Decompose the Application

  • Create use cases to understand how the application is used

  • Identifying entry points to see where a potential attacker could interact with the application

  • Identifying assets (items or areas that the attacker would be interested in)

  • Identifying trust levels that represent the access rights that the application will grant to external entities

  • Data flow diagrams can help illustrate

11.3. 2. Determine and Rank Threats

  • Use a threat categorization methodology

    • STRIDE

    • Application Security FRAME

    • PASTA

    • DREAD

  • Identify threats from the attacker

  • Identify the defensive perspective

  • Use threats to build threat trees

    • One tree for each threat goal

11.4. STRIDE Overview

Threat Desired Property

Spoofing

Authenticity

Tampering

Integrity

Repudiation

Non-repudiation

Information disclosure

Confidentiality

Denial of service

Availability

Elevation of privilege

Authorization

11.5. DREAD Risk Assessment

Threat Category Description

Damage

How bad would an attack be?

Reproducibility

How easy is it to reproduce the attack?

Exploitability

How much work is it to launch the attack?

Affected users

How many people will be impacted?

Discoverability

How easy is it to discover the threat?

11.6. Data flow

data flow diagram 7

12. MongoDB Security Best Practices

|== |Objectives

a|Key objectives of this chapter

  • Discuss MongoDB security best practices

  • Learn about MongoDB database encryption |==

12.1. Use strong authentication mechanisms:

  • MongoDB provides several authentication mechanisms

    • SCRAM

    • x.509

    • LDAP

  • Create separate users with different roles to limit access

12.2. Limit remote access

  • Reduces the risk of data leaks

  • Recommended to whitelist specific IP addresses for remote connections

12.3. Implement role-based access control

  • Use role-based access control to define and enforce access permissions for different users or processes accessing MongoDB

  • Helps ensure that only authorized users have the necessary privileges

12.4. Encrypt your data

  • Encrypting your data adds an extra layer of security

  • MongoDB provides features for data encryption, including encryption at rest and encryption in transit

  • Implementing encryption helps protect sensitive data from unauthorized access

12.5. Keep MongoDB up to date

  • Regularly update MongoDB to the latest version to ensure that you have the latest security patches and bug fixes

  • MongoDB releases updates and security patches to address vulnerabilities and improve security

12.6. Implement proper input validation

  • Ensure that you properly validate and sanitize user input to prevent common security vulnerabilities such as

    • NoSQL injection

    • Cross-site scripting (XSS) attacks

12.7. Enable auditing and monitoring

  • Enable auditing and monitoring features provided by MongoDB to track and log activities in the database

  • Can help detect and investigate any suspicious or unauthorized activities

12.8. Encrypting Data in MongoDB

  • To encrypt data in MongoDB, you can use the Client-Side Field Level Encryption (CSFLE) feature.

  • IMPORTANT: MongoDB cannot encrypt existing data (If you have existing data, you’ll need to follow additional steps to encrypt it.)

  • MongoDB also provides encryption at rest, which encrypts the data files stored on disk, ensures that the data remains encrypted even if the physical storage is compromised

=HTTP Security Headers

Objectives

Key objectives of this chapter

  • Learn about HTTP security headers

  • Discuss helmet.js

12.9. What are HTTP Security Headers?

  • HTTP Security Headers are a set of response headers that instruct the browser on how to behave when handling your web application.

  • These headers add an extra layer of security, preventing various attacks and vulnerabilities.

  • Some common security headers include Content Security Policy (CSP), X-XSS-Protection, X-Frame-Options, etc.

12.10. helmet.js

  • A crucial security package that helps secure your HTTP headers and protect your MERN applications from common web vulnerabilities.

12.11. Why Use helmet.js?

  • Writing these headers manually can be cumbersome and error-prone.

  • helmet.js simplifies the process by providing an easy-to-use middleware to set these headers securely.

  • It is widely used, well-maintained, and compatible with Express.js, a popular framework in MERN stack development.

12.12. Installing helmet.js

  • Before using helmet.js, we need to install it in our MERN application.

  • Open your terminal and run: npm install helmet

12.13. Implementing helmet.js

  • Import helmet in your Express.js server file:

const express = require('express');
const helmet = require('helmet');
const app = express();

// Use helmet middleware
app.use(helmet());

12.14. Content Security Policy (CSP)

  • A critical security header is Content Security Policy (CSP)

  • CSP restricts the sources from which your application can load content, mitigating XSS and data injection attacks

  • Implement CSP using helmet.js

const express = require('express');
const helmet = require('helmet');
const app = express();

// Use helmet middleware with Content Security Policy
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'"],
    styleSrc: ["'self'", "'unsafe-inline'"]
  }
}));

12.15. X-XSS-Protection and X-Frame-Options

  • X-XSS-Protection header enables the browser’s Cross-Site Scripting (XSS) filter

  • X-Frame-Options prevents your application from being embedded in a frame on another site, mitigating clickjacking attacks

const express = require('express');
const helmet = require('helmet');
const app = express();

// Use helmet middleware with X-XSS-Protection and X-Frame-Options
app.use(helmet.xssFilter());
app.use(helmet.frameguard({ action: 'sameorigin' }));

13. React Security Best Practices

Objectives

Key objectives of this chapter

  • Discuss security best practices particular to React

  • Explore resources for React security

13.1. The React Virtual DOM is not enough

React Logo
  • The Virtual DOM provides some security benefits

  • Does not address all security concerns and should be part of a broader security strategy

  • Consider:

    • Security Vulnerabilities in Dependencies

    • Server-Side Rendering (SSR) Vulnerabilities

    • Proper Use of Props and State

13.2. Regularly update third-party packages and dependencies

  • Keeping your packages and dependencies up to date helps reduce vulnerabilities

  • Make sure to regularly check for updates and apply them to your project

13.3. Encrypt sensitive data

  • Ensure that sensitive data is encrypted both when stored and transmitted over the network

  • Helps protect the confidentiality of the data

  • Use encryption libraries or frameworks to implement encryption in your React application

13.4. Implement authentication and authorization

  • Properly authenticate and authorize users to access your application

  • Use secure authentication mechanisms such as JSON Web Tokens (JWT)

  • Implement authorization checks to control access to different parts of your application

13.5. Validate and sanitize user input

  • Validate and sanitize user input to prevent common security vulnerabilities such as cross-site scripting (XSS) and SQL injection attacks

  • Use libraries or frameworks that provide input validation and sanitization features

13.6. Protect against cross-site scripting (XSS) attacks

  • XSS attacks can be prevented by properly validating and sanitizing user input

  • Use security headers like Content Security Policy (CSP) to mitigate the risk of XSS attacks

13.7. Securely handle session management

  • If your application uses sessions, make sure to handle session management securely

  • Use secure session storage mechanisms and implement measures to prevent session hijacking or session fixation attacks

13.8. Implement secure communication

  • Use secure communication protocols such as HTTPS to encrypt the communication between the client and server

  • Helps protect the integrity and confidentiality of the data transmitted over the network

13.9. Follow React security best practices

  • Familiarize yourself with React-specific security best practices

  • This includes disabling any instruction-containing markup, using snippet libraries, conducting code audits, and following React security checklists

13.10. Keep your code modular and readable

  • Writing modular and readable code helps improve maintainability and reduces the risk of introducing security vulnerabilities

  • Follow best practices for code organization, naming conventions, and documentation for your team

13.11. Perform security testing

  • Regularly perform security testing on your application to identify and address any security vulnerabilities

  • This can include manual code reviews, automated security scanning, and penetration testing

14. Node Security Best Practices

|== |Objectives

a|Key objectives of this chapter

  • Discuss best practices to keep Node secure

  • Explore resources to secure Node |==

14.1. Node in the application flow

node and express

14.2. Regularly update packages and dependencies

  • Keep your codebase up to date by regularly updating third-party packages and dependencies

  • Helps to reduce vulnerabilities and ensures that you are using the latest security patches

14.3. Encrypt sensitive data

  • Ensure that sensitive data is encrypted both when stored and transmitted over the network

  • Helps to protect the confidentiality of the data and prevent unauthorized access

14.4. Implement secure authentication

  • Follow best practices for secure authentication in MERN stack applications

  • This includes using:

    • Strong password hashing algorithms

    • Implementing multi-factor authentication

    • Protecting against common vulnerabilities such as SQL injections and cross-site scripting (XSS) attacks

14.5. Use security linters and scanners

  • Take advantage of security linters, such as ESLint with security rules or Snyk, to identify and fix potential security issues in your code

  • These linters can help catch common security vulnerabilities and enforce best practices

14.6. Secure transmission of data

  • Ensure that data transmitted over the network is done securely using HTTPS

  • Helps to protect the integrity and confidentiality of the data during transit

14.7. Control access and permissions

  • Implement proper access controls and permissions to restrict unauthorized access to sensitive resources

  • Use role-based access control (RBAC) or other access control mechanisms to enforce least privilege principles

14.8. Validate and sanitize user input

  • Always validate and sanitize user input to prevent common security vulnerabilities such as SQL injections and cross-site scripting (XSS) attacks

  • Use input validation techniques and sanitize user input before using it in database queries or rendering it in HTML templates

14.9. Implement logging and monitoring

  • Set up logging and monitoring mechanisms to track and detect any suspicious activities or security incidents

  • Monitor logs and system metrics to identify potential security breaches and respond to them in a timely manner

14.10. Perform security testing

  • Conduct regular security testing, including vulnerability scanning and penetration testing, to identify and address any security weaknesses in your application

  • Helps to identify and fix vulnerabilities before they can be exploited by attackers

14.11. Follow security best practices for the entire MERN stack

  • Remember that security is not limited to just Node.js

  • Ensure that you follow security best practices for all components of the MERN stack

14.12. Security is a PROCESS

  • Security is a continuous process

  • Stay informed about the latest security vulnerabilities

  • Seek out groups and mentors to support you